import React, { useState, useEffect } from 'react'
import Title from './component/xitong_Title'
import Flushed from '../../Monitoring_analytics/Operate_monitor/Component/Flushed';

import { Table, Tooltip, Space, Button, Flex } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import { getuser, deluser, edituser, updateuser, getcos } from '../../../request/api'


import { Input, Modal, Form, Select } from 'antd';

export default function Account_management() {
  useEffect(() => {
    alluser()
    cosshange()
  }, [])

  // 获取全部的用户信息
  let [userdata, setdata] = useState([])
  const alluser: any = async () => {
    const data: any = await getuser({})
    console.log(data);

    setdata(data.data)
  }

  // 获取子组件传递的搜索完后的数据信息，更新用户信息
  const getTitle = (item: any) => {
    console.log(item);
    setdata(item)
  }

  // 删除用户信息
  const userdelete = async () => {
    if (selectedRowKeys.length == 0) {
      alert('请选择要删除的用户')
    } else {
      let data = await deluser({ list_id: selectedRowKeys })
      if (data.code == 200) {
        alert('删除成功')
        setSelectedRowKeys([])
        alluser()
      }
    }

  }

  // 添加用户之后获取最新的用户数据
  const getuserlist = (item: any) => {
    if (item == 200) {
      alluser()
    }
  }


  // 数据回显
  const [modal2Open, setModal2Open] = useState(false); //控制模态框是否显示
  const getupdata = async () => {
    if (selectedRowKeys.length < 1) {
      alert('请选择要修改的用户')
    } else if (selectedRowKeys.length > 1) {
      alert('只能选择一个用户进行修改')
    } else {
      let data = await edituser({ list_id: selectedRowKeys })
      console.log(data.data[0]);
      setModal2Open(true)
      set_id(data.data[0]._id)
      setuser(data.data[0].user)
      setReal_name(data.data[0].Real_name)
      setpassword(data.data[0].password)
      setphone(data.data[0].phone)
      setcos(data.data[0].cos)
    }
  }

  // 修改数据
  const updata = async () => {
    let from = {
      user: user,
      Real_name: Real_name,
      password: password,
      phone: phone,
      cos: cos,
      _id: _id
    }
    let data = await updateuser({ from })
    if (data.code == 200) {
      setModal2Open(false)
      alluser()
    }
  }

  // 角色回显
  let [coslist, setcoslist] = useState([])//角色列表
  const cosshange = async () => {
    let res = await getcos({})
    setcoslist(res.data)
  }




  type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
  const columns: TableColumnsType = [
    { title: '账号', dataIndex: 'user', key: 'user' },
    { title: '姓名', dataIndex: 'Real_name', key: 'Real_name' },
    { title: '手机号', dataIndex: 'phone', key: 'phone' },
    { title: '角色', dataIndex: 'cos', key: 'cid' },
    { title: '创建时间', dataIndex: 'static_time', key: 'static_time' },
    {
      title: '操作',
      key: '_id',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => {
            getupdata()
          }}>编辑 </a>
          <a onClick={() => {
            userdelete()
          }}>删除</a>
        </Space>
      ),
    },
  ];




  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);

  const start = () => {
    setLoading(true);
    let time = setTimeout(async () => {
      let data = await deluser({ list_id: selectedRowKeys })
      if (data.code == 200) {
        alert('删除成功')
        setSelectedRowKeys([]);
        setLoading(false);
        alluser()
        clearTimeout(time)
      }
    }, 1000);
  };


  // 数据渲染
  const dataSource = userdata.map((item) => ({
    key: item._id,
    user: item.user,
    cos: item.cos,
    static_time: item.static_time,
    Real_name: item.Real_name,
    phone: item.phone,
  }));


  // 选择项
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;




  const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');
  const onFormLayoutChange = ({ size }: { size: SizeType }) => {
    setComponentSize(size);
  };


  let [_id, set_id] = useState('')//id
  let [user, setuser] = useState([])//账号
  let [password, setpassword] = useState([])//密码
  let [phone, setphone] = useState([])//手机号
  let [cos, setcos] = useState([])//角色
  let [Real_name, setReal_name] = useState([])//姓名




  return (
    <div>
      <Title name='创建账号' fct={getTitle} getuserlist={getuserlist} />
      <Flushed></Flushed>
      <div style={{ width: '100%', backgroundColor: 'white', padding: '0.5rem', marginTop: '0.5rem' }}>
        <Flex gap="middle" vertical>
          <Flex align="center" gap="middle">
            <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
              批量删除
            </Button>
            {hasSelected ? `当前选中 ${selectedRowKeys.length} 条数据` : null}
          </Flex>
          <Table rowSelection={rowSelection} columns={columns} dataSource={dataSource} />
        </Flex>
      </div>

      <Modal
        title='修改数据'
        centered
        open={modal2Open}
        onOk={() => updata()}
        onCancel={() => setModal2Open(false)}
      >
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          initialValues={{ size: componentSize }}
          onValuesChange={onFormLayoutChange}
          size={componentSize as SizeType}
          style={{ maxWidth: 600 }}
        >
          <Form.Item label="账号">
            <Input value={user} onChange={(e) => {
              setuser(e.target.value)
            }} />
          </Form.Item>
          <Form.Item label="角色" >
            <Select value={cos} onChange={(e) => {
              setcos(e)
            }}>
              {coslist.map((item) => {
                return <Select.Option key={item._id} value={item._id}>{item.identity_name}</Select.Option>
              })
              }

            </Select>
          </Form.Item>
          <Form.Item label="姓名">
            <Input value={Real_name} onChange={(e) => {
              setReal_name(e.target.value)
            }} />
          </Form.Item>
          <Form.Item label="手机号">
            <Input value={phone} onChange={(e) => {
              setphone(e.target.value)
            }} />
          </Form.Item>
          <Form.Item label="密码">
            <Input value={password} onChange={(e) => {
              setpassword(e.target.value)
            }} />
          </Form.Item>
        </Form>

      </Modal>
    </div>
  )
}
